package com.bdqn.bookshop.interceptor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bdqn.bookshop.dao.MallUserMapper;
import com.bdqn.bookshop.entity.MallUser;
import com.bdqn.bookshop.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private MallUserMapper mallUserMapper;

    MallUser mallUser;

    //之前执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        // 获得cookie
        Cookie[] cookies = request.getCookies();
        // 没有cookie信息，则重定向到登录界面
        if (null == cookies) {
            response.sendRedirect(request.getContextPath()+"/mall/join.html#tologin");
            return false;
        }
        String username = null;
        String password=null;
        // 获取cookie里面的一些用户信息
        for (Cookie item : cookies) {
            if ("username".equals(item.getName())) {
                username = item.getValue();
                break;
            }
        }

        for (Cookie cookie : cookies) {
            if ("password".equals(cookie.getName())){
                password=cookie.getValue();
                break;
            }
        }


        // 获取HttpSession对象
        HttpSession session = request.getSession();
        // 获取我们登录后存在session中的用户信息，如果为空，表示session已经过期
        Object obj  = session.getAttribute("mallUser");
        if ( obj==null) {
            // 根据用户登录账号获取数据库中的用户信息
            QueryWrapper<MallUser> queryWrapper=new QueryWrapper<MallUser>();
            queryWrapper.eq( "user_Name",username);
            queryWrapper.eq("password",password);

            mallUser=mallUserMapper.selectOne(queryWrapper);
            // 将用户保存到session中
            session.setAttribute("mallUser", mallUser);
        }


        // 已经登录
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }


}
